package xyz.mimai.media.netty.taskQueue;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;

import java.nio.charset.Charset;

/**
 * @ClassName Client
 * @Description TODO
 * @Author 方丈
 * @Date 2021/2/4 9:34
 * @Version 1.0.0
 **/
public class Client {
    public static void main(String[] args) {
        //客户端只需要一个事件组就够了
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();

        try {
            //客户端启动对象
            Bootstrap bootstrap = new Bootstrap();

            bootstrap.group(eventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new SelfDefineClientHandler());
                        }
                    });
            System.out.println("客户端启动完成，准备连接服务器...");
            ChannelFuture sync = bootstrap.connect("127.0.0.1", 7777).sync();
            sync.channel().closeFuture().sync();
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            eventLoopGroup.shutdownGracefully();
        }

    }

    /**
     * 自定义业务处理
     */
    public static class SelfDefineClientHandler extends ChannelInboundHandlerAdapter{

        /** 
         * @description  必须将消息编码，否则无法发送
         * @author 方丈
         * @date 2021-02-04 10:14
         * @param	nativeMsg	
         * @return io.netty.buffer.ByteBuf
         * @since 1.0.0
         */
        private ByteBuf buildNettyMsg(String nativeMsg){
            return Unpooled.copiedBuffer(nativeMsg, CharsetUtil.UTF_8);
        }

        @Override
        public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
         //   super.channelRegistered(ctx);
            System.out.println("通道注册成功");

            //实际上这一句无法发送消息，在active以后才可能发送到服务端
            ctx.writeAndFlush(buildNettyMsg("channel is ready"));
        }

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
         //   super.channelActive(ctx);
            System.out.println("通道连接就绪，发送消息...");
            ctx.writeAndFlush(buildNettyMsg("你好，服务器，业务来了"));
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            ByteBuf bb =(ByteBuf) msg;
            String recvContent  = bb.toString(Charset.forName("utf-8"));
            System.out.println("接收到了服务端的应答消息："+recvContent);
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
          //  super.exceptionCaught(ctx, cause);
            System.out.println("发生了异常... ...");
            cause.printStackTrace();
            ctx.close();
        }
    }
}
